import React from 'react'
import { connect } from 'dva'
import { Tree, Row, Col, Button, Icon, message, Input } from 'antd'
import { ROOT_ID } from 'utils/organizationConstant'
import { getByField } from 'utils/helpers'
import font from './font.less'

const TreeNode = Tree.TreeNode
const Search = Input.Search

const OrganizationTree = ({
                            dataSource = [],
                            showLine = true,
                            showIcon = true,
                            defaultExpandAll = false,
                            distributorType = 'create',
                            onSelect,
                            dispatch,
                            searchKeyword = '',
                          }) => {
  // 当选中的节点
  let currentSelectedNode = {}
  // 获取根节点
  const rootNode = getByField(dataSource, 'parentId', ROOT_ID)
  // 处理源数据,生成树形结构
  const dealedSourceData = (function loop (data) {
    let temp = []
    let lev = 0
    // 如果有搜索，就先过滤搜索
    if (searchKeyword !== '') {
      data = searchData(data, searchKeyword)
    }
    data.forEach((val, index) => {
      if (val.parentId === rootNode.id) {
        val.key = `0-${index}`
        data[index].key = `0-${index}`
        temp.push(val)
      }
    })

    // 查找子元素
    function findChild (temp) {
      temp.forEach((col, i) => {
        if (find(col.id).length > 0) {
          col.children = find(col.id)
          col.children.forEach((con, num) => {
            con.key = col.key + '-' + num
            data.forEach((val, index) => {
              if (val.id === con.id) {
                val.key = col.key + '-' + num
              }
            })

          })
          findChild(col.children)
        }

      })
      return temp
    }

    // 看是否有子元素
    function find (id) {
      let temp = []
      data.forEach(v => {
        if (v.parentId === id) {
          temp.push(v)
        }
      })
      return temp
    }

    function findParents (parentId, items = []) {
      let temp = data.filter(item => {
        return item.id === parentId && item.parentId !== ROOT_ID
      })

      if (temp.length > 0) {
        items.concat(temp)
        // 继续递归
        findParents(temp[0].parentId, temp)
      }

      return temp
    }

    function searchData (data, keyword) {
      let temp = data.filter(item => {
        return item.name.indexOf(keyword) !== -1
      })

      // 在data中寻找对应的父级，直到顶级
      let returnData = []
      temp.forEach((item) => {
        returnData = returnData.concat([item].concat(findParents(item.parentId)))
      })

      return [...new Set(returnData)].sort((a, b) => a.priority < b.priority ? -1 : 1)
    }

    temp = findChild(temp)
    return ({data, temp})
  })(dataSource)

  //处理原数据
  const loop = (data) => data.map((item) => {
    if (item.children) {
      return <TreeNode
        title={item.name}
        key={item.key}
        // icon={item.enabled ? <Icon type="check" /> : <Icon type="close" />}
        disabled={item.disabled}
        pid={item.parentId}
        id={item.id}
      >{loop(item.children)}</TreeNode>
    }
    return <TreeNode
      title={item.name}
      key={item.key}
      // icon={item.enabled ? <Icon type="check" /> : <Icon type="close" />}
      pid={item.parentId}
      disabled={item.disabled}
      id={item.id}
    />
  })

  // 点击节点预处理
  const pretreatSelect = (selectedKeys) => {
    let selectedData = {}
    if (selectedKeys.length > 0) {
      selectedData = _.find(dealedSourceData.data, (d) => {
        return d.key === selectedKeys[0]
      })
    }

    currentSelectedNode = selectedData
    if (onSelect) {
      onSelect(selectedData)
    }
  }

  const ColProps = {
    xs: 24,
    sm: 12,
    style: {
      marginBottom: 16
    }
  }

  const TwoColProps = {
    ...ColProps,
    xl: 96
  }

  /** @namespace info.dragNode.props.eventKey */
  /** @namespace info.dragNode */
  /** @namespace info.dropPosition */
  /** @namespace info.dropToGap */
  const onDrop = (info) => {
    console.info(info)
    let levelDrop = false;
    if (info.node.props.pid !== info.dragNode.props.pid) {
      levelDrop = true;
    }

    dispatch({
      type: 'organization/dragNode',
      payload: info
    })
    dispatch({
      type: 'organization/onDrag',
      payload: {
        tree: dataSource,
        dragNode: info.dragNode.props,
        node: info.node.props,
        levelDrop:levelDrop
      }
    })
  }

  const onChange = (e) => {
    const value = e.target.value
    dispatch({
      type: 'organization/setSearchKeyword',
      payload: {keyword: value}
    })
  }

  return (
    <div>
      <Search style={{marginBottom: 8, width: 200}} placeholder="搜索" onChange={onChange}/>
      <Tree
        defaultExpandAll={defaultExpandAll}
        onSelect={pretreatSelect}
        showLine={showLine}
        showIcon={showIcon}
        draggable={true}
        onDrop={onDrop}
      >
        {loop(dealedSourceData.temp)}
      </Tree>
    </div>
  )
}

export default OrganizationTree
